<?php
namespace Admin\Controller;

use Think\Page;

class ExpresssettingController extends CommonController
{
    public $model = null;

    public function __construct()
    {
        parent::__construct();
        $this->model = M('express_setting');
    }

    /**
     * 数据列表
     * @return [type]
     */
    public function index()
    {
        $where = [];

        $count = $this->model->where($where)->count();
        $this->assign('count', $count);

        $pages = new Page($count, C('PAGE'), $fields);
        $this->assign('pages', $pages->show());

        $datas = $this->model->where($where)
            ->order('id desc')
            ->limit($pages->firstRow . ',' . $pages->listRows)
            ->select();
        $this->assign('datas', $datas);

        $this->assign('bread_crumb', $bread_crumb = generate_bread_crumb([
            '系统设置',
            '快递平台设置',
        ]));
        $this->display();
    }

    public function update()
    {
        if (IS_GET) {

            $id = I('get.id', 0, 'intval');

            $data         = $this->model->find($id);
            $data['conf'] = json_decode($data['conf'], true);
            $this->assign('data', $data);

            $this->assign('bread_crumb', $bread_crumb = generate_bread_crumb([
                '系统设置',
                '快递平台【' . $data['name'] . '】配置信息修改',
            ]));
            $this->display();

        } elseif (IS_POST) {

            $id = I('post.id', 0, 'intval');

            $data = [
                'is_open'    => I('post.is_open', '', 'trim'),
                'is_default' => I('post.is_default', '', 'trim'),
            ];

            $eBusinessID = I('post.eBusinessID', '', 'trim');
            $appKey      = I('post.appKey', '', 'trim');

            if ($data['is_open'] == 'on') {
                $data['is_open'] = 1;
            } else {
                $data['is_open'] = 0;
            }

            if ($data['is_default'] == 'on') {
                $data['is_default'] = 1;
            } else {
                $data['is_default'] = 0;
            }

            if ($eBusinessID && $appKey) {
                $data['conf'] = json_encode([
                    'eBusinessID' => $eBusinessID,
                    'appKey'      => $appKey,
                ]);
            }

            $this->model->where(['id' => $id])->save($data);

            $this->success('修改成功', U(CONTROLLER_NAME . '/update', [
                'id' => $id,
            ]));
        }
    }
}
